<?php

namespace app\service;

use app\model\Fish;
use app\model\UserFish;
use extend\Random;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserFishService extends BaseService
{


    //添加玩家鱼
    public function add_user_fish($user_id, $fish_id, $num): array
    {
        //查询卡牌是否存在
        $fish = Fish::where("id", $fish_id)->find();
        if (!$fish) {
            return $this->returnFail("卡牌不存在");
        }

        //查询玩家是否已经拥有该卡牌碎片
        $user_fish = UserFish::where("user_id", $user_id)->where("fish_id", $fish_id)->find();
        if (!$user_fish) {
            $user_fish = new UserFish();
            $user_fish->user_id = $user_id;
            $user_fish->fish_id = $fish_id;
        }
        $user_fish->num = $user_fish->num + $num;
        $user_fish->save();

        return $this->returnSuccess("添加成功");
    }



    /**
     * 获取鱼谱
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function get_fish_guide(): array
    {
        $fish_list = (new Fish())->select();
        return $this->returnSuccess($fish_list->toArray());
    }


    //根据概率随机获取钓取的鱼
    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function get_random_fish($user_id,$probability): array
    {
        //获取鱼的类型
        $fish_type = Random::lottery($probability);
        $fish = (new Fish())->where('type', $fish_type)->orderRand()->find();
        if (empty($fish)) {
            return $this->returnFail(0, '没有获取到鱼');
        }

        //把鱼放用户的鱼缸里
        $user_fish_model = new UserFish();
        $user_fish_model->user_id = $user_id;
        $user_fish_model->yu_id = $fish->id;
        $res = $user_fish_model->save();
        if (empty($res)) {
            return $this->returnFail(0, '放入鱼缸失败');
        }
        //去除多余字段
        $fish = $this->handleModelData($fish);
        return $this->returnSuccess($fish->toArray());
    }


}